<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select
          v-model="dateType"
          style="width: 120px; margin-right: 2px;"
        >
          <el-option label="创建时间" value="createTime" />
          <el-option label="计划执行时间" value="executeDate" />
          <el-option label="实际完成时间" value="finishDate" />
          <el-option label="更新时间" value="modifyTime" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="调拨车辆:" prop="truckCode">
        <el-select
          v-model="query.truckCode"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in truckList"
            :key="item.truckCode"
            :label="item.truckCode"
            :value="item.truckCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="司机:" prop="driverId">
        <el-select
          v-model="query.driverId"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in driverList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-select
          v-model="query.status"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in statusMap"
            :key="item.key"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="押运员:" prop="escortId">
        <el-select
          v-model="query.escortId"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in escortList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="1" class="merge-item">
        <el-select
          v-model="userType"
          style="width: 130px; margin-right: 2px;"
        >
          <el-option label="创建人" value="createUser" />
          <el-option label="完成人" value="completeUser" />
          <el-option label="作废人" value="cancelUser" />
        </el-select>
        <el-input
          v-model="userName"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="计划单号:" prop="planCode">
        <el-input
          v-model.trim="query.planCode"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="起点站:" prop="startOrgId">
        <el-tree-select
          ref="treeSelect"
          v-model="query.startOrgId"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            filterable:true,
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @search-clear="searchClear"
        />
      </el-form-item>
      <el-form-item label="终点站:" prop="endOrgId">
        <el-tree-select
          ref="treeSelect"
          v-model="query.endOrgId"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            filterable:true,
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @search-clear="searchClear"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[70301,1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
        <el-button
          icon="el-icon-refresh"
          @click="reset"
        >重置</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          v-permission="[70301,2]"
          type="primary"
          icon="el-icon-plus"
          @click="addAllotPlan"
        >调拨计划</el-button>
        <el-button
          v-permission="[70301,6]"
          :loading="$loadingPlugin.exportFile"
          type="primary"
          icon="el-icon-download"
          @click="exportFile"
        >导出</el-button>
      </div>
    </div>

    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <!-- <edit-info ref="editInfo" @upDataTable="upDataTable" /> -->
    <allot-plan-detail ref="allotPlanDetail" :status-map="statusMap" :truck-list="truckList" :driver-list="driverList" :escort-list="escortList" />
    <allotInfo ref="allotInfo" />
    <allotPlanEdit ref="allotPlanEdit" :truck-list="truckList" :driver-list="driverList" :escort-list="escortList" :tree-data="treeData" />
  </div>
</template>

<script>
  import {
    queryTruckNoList,
    queryDriverList,
    queryEscortList,
    queryExportDomain,
    queryMap,
    stockTransPlanList,
    stockTransPlanCancel,
    stockTransPlanFinish,
    stockTransPlanExport
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { mapGetters } from 'vuex'
  import { formatColumnMap, parseTime } from '@/utils'
  import allotInfo from './components/allotInfo'
  import allotPlanEdit from './components/allotPlanEdit'
  import allotPlanDetail from './components/allotPlanDetail'

  import dayjs from 'dayjs'
  export default {
    name: 'allotPlan',
    components: {
      allotInfo, allotPlanEdit, allotPlanDetail
    },
    data() {
      return {
        dateType: 'createTime',
        date: [dayjs(new Date()).format('YYYY-MM-DD') + ' ' + '00:00:00', dayjs(new Date()).format('YYYY-MM-DD') + ' ' + '23:59:59'],
        userType: 'createUser',
        userName: '',
        query: {
          truckCode: '',
          driverId: '',
          escortId: '',
          planCode: '',
          status: '',
          startOrgId: '',
          endOrgId: ''
        },
        treeData: [],
        truckList: [],
        driverList: [],
        escortList: [],
        stationList: [],
        statusMap: [],
        actionColWidth: 80,
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'planCode',
            label: '调拨计划单号',
            width: 120,
            render: (h, { row }) => (
              <el-link underline={false} onClick={() => this.showDetail(row)}>
                {row.planCode}
              </el-link>
            )
          },
          {
            prop: 'status',
            label: '状态',
            render: (h, scope) => (
              <span>
                {scope.row.status &&
                formatColumnMap(
                  this.statusMap,
                  'value',
                  scope.row.status,
                  'desc'
                )}
              </span>
            )
          },
          {
            prop: 'bottleNum',
            label: '调拨数量'
          },
          {
            prop: 'billNum',
            label: '关联调拨单',
            width: 100,
            render: (h, { row }) => (
              <el-link underline={false} onClick={() => this.showAllotInfo(row)}>
                {row.billNum}
              </el-link>
            )
          },
          {
            prop: 'startOrgName',
            label: '起点站',
            width: 100
          },
          {
            prop: 'endOrgName',
            label: '终点站',
            width: 100
          },
          {
            prop: 'truckCode',
            label: '车辆',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'driverName',
            label: '司机',
            width: 100
          },
          {
            prop: 'escortName',
            label: '押运员'
          },
          {
            prop: 'remarks',
            label: '备注'
          },
          {
            prop: 'createUser',
            label: '创建人'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 160,
            render: (h, { row }) => (
              <span>
                {row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
          },
          {
            prop: 'executeDate',
            label: '计划执行日期',
            width: 160,
            render: (h, { row }) => (
              <span>
                {row.executeDate && parseTime(row.executeDate, '{y}-{m}-{d}')}
              </span>
            )
          },
          {
            prop: 'finishUser',
            label: '完成人'
          },
          {
            prop: 'finishDate',
            label: '实际完成日期',
            width: 160,
            render: (h, { row }) => (
              <span>
                {row.finishDate && parseTime(row.finishDate, '{y}-{m}-{d}')}
              </span>
            )
          },
          {
            prop: 'cancelUser',
            label: '作废人'
          },
          {
            prop: 'cancelDate',
            label: '作废时间',
            width: 160,
            render: (h, { row }) => (
              <span>
                {row.cancelDate && parseTime(row.cancelDate, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
          },
          {
            prop: 'modifyTime',
            label: '更新时间',
            width: 160,
            render: (h, { row }) => (
              <span>
                {row.modifyTime && parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
          },
          {
            label: '操作',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {(row.status === 1 || row.status === 2 || row.status === 3) && (
                    <el-link
                      v-permission={[70301, 3]}
                      underline={false}
                      size='mini'
                      onClick={() => this.editPlanAllot(row)}
                    >
                      {' '}
                      编辑{' '}
                    </el-link>
                  )}
                  {row.status === 3 && (
                    <el-link
                      v-permission={[70301, 5]}
                      underline={false}
                      size='mini'
                      onClick={() => this.completeHandler(row, $index)}
                    >
                      完成计划
                    </el-link>
                  )}
                  {(row.status === 1) && (
                    <el-link
                      v-permission={[70301, 4]}
                      underline={false}
                      type='danger'
                      size='mini'
                      onClick={() => this.delHandler(row, $index)}
                    >
                      {' '}
                      作废{' '}
                    </el-link>
                  )}
                </div>
              )
            }
          }
        ]
      },
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      this.getTreeData()
      this.queryOptionsMap()
      this.initStoreMap()
      this.getExportDomain()
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      // selectTreeChange(value) {
      //   this.orgSNNo = value.orgSNNo
      // },
      searchClear() {
        if (this.$refs.treeSelect) this.$refs.treeSelect.keywords = ''
      },
      async fetchData({ currentPage, pageSize }) {
        const params = {
          ...this.query,
          currentPage: currentPage,
          pageSize
        }

        if (this.dateType && this.date && this.date.length) {
          params[this.dateType + 'Start'] = this.date[0]
          params[this.dateType + 'End'] = this.date[1]
        }
        if (this.userType && this.userName) {
          params[this.userType] = this.userName
        }
        const res = await stockTransPlanList(params)
        if (res.data) {
          this.tableData.data = res.data.rows
          if (currentPage === 1) this.tableData.total = res.data.total
        }
        this.flexColumnWidth()
      },
      async initStoreMap() {
        // 查询所有车辆
        const query = {
          truckType: 3
        }
        const res1 = await queryTruckNoList(query)
        this.truckList = res1.data
        // 查询所有司机
        const res2 = await queryDriverList()
        this.driverList = res2.data
        // 查询所有押运员
        const res3 = await queryEscortList()
        this.escortList = res3.data
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res] = await Promise.all([
          queryMap({ enumName: 'StockTransPlanStatusEnum' })
        ])
        this.statusMap = res.data
      },
      // 查看调拨计划详情
      showDetail(row) {
        this.$refs.allotPlanDetail.open(row)
      },
      // 查看调拨单信息
      showAllotInfo(row) {
        this.$refs.allotInfo.open(row)
      },
      // 新增调拨计划
      async addAllotPlan() {
        await this.$refs.allotPlanEdit.open('add')
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 完成计划操作
      async completeHandler(row) {
        this.$confirm('请确认是否完成当前调拨计划？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在完成',
            duration: 0,
            iconClass: 'el-icon-loading'
          })

          stockTransPlanFinish({ id: row.id })
            .then(() => {
              this.search()
              this.$notify({
                title: '提示',
                message: '已完成',
                type: 'success',
                duration: 2000
              })
            })
            .finally(() => {
              loading.close()
            })
        })
      },
      // 作废单据
      delHandler(row) {
        this.$confirm('请确认是否作废当前调拨计划？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在作废',
            duration: 0,
            iconClass: 'el-icon-loading'
          })

          stockTransPlanCancel({ id: row.id })
            .then(() => {
              this.search()
              this.$notify({
                title: '提示',
                message: '已作废',
                type: 'success',
                duration: 2000
              })
            })
            .finally(() => {
              loading.close()
            })
        })
      },
      // 编辑
      async editPlanAllot(row) {
        await this.$refs.allotPlanEdit.open('edit', row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 单号
      stockCodeHandle(row) {
        this.$refs.editInfo.open(row, 'detail')
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      reset() {
        this.dateType = 'createTime'
        this.date = [dayjs(new Date()).format('YYYY-MM-DD'), dayjs(new Date()).format('YYYY-MM-DD')]
        this.userType = 'createUser'
        this.userName = ''
        this.$refs.form.resetFields()
      },
      async update(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      // 导出
      async exportFile() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const query = {
            ...this.query
          }
          if (this.dateType && this.date.length) {
            query[this.dateType + 'Start'] = this.date[0]
            query[this.dateType + 'End'] = this.date[1]
          }
          if (this.userType && this.userName) {
            query[this.userType] = this.userName
          }
          stockTransPlanExport({
            paramInfo: query,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
